import React, { useState, useEffect } from 'react';
import {
  Table,
  Button,
  Space,
  Modal,
  Form,
  Input,
  Select,
  DatePicker,
  message,
  Popconfirm,
  Card,
  Row,
  Col,
  Tag,
  Tooltip
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  ExportOutlined,
  ImportOutlined,
  SearchOutlined,
  ReloadOutlined,
  LockOutlined,
  UnlockOutlined
} from '@ant-design/icons';
import { CustomerApi, CustomerVO, CustomerPageParams } from '../../../api/crm/customer';

const { Option } = Select;
const { RangePicker } = DatePicker;

const CustomerManagement: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [customers, setCustomers] = useState<CustomerVO[]>([]);
  const [total, setTotal] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [searchParams, setSearchParams] = useState<CustomerPageParams>({});
  const [modalVisible, setModalVisible] = useState(false);
  const [editingCustomer, setEditingCustomer] = useState<CustomerVO | null>(null);
  const [form] = Form.useForm();

  // 客户等级选项
  const levelOptions = [
    { label: '普通客户', value: 1 },
    { label: 'VIP客户', value: 2 },
    { label: '重要客户', value: 3 }
  ];

  // 客户来源选项
  const sourceOptions = [
    { label: '线上推广', value: 1 },
    { label: '电话营销', value: 2 },
    { label: '客户介绍', value: 3 },
    { label: '展会', value: 4 },
    { label: '其他', value: 5 }
  ];

  // 获取客户列表
  const fetchCustomers = async () => {
    setLoading(true);
    try {
      const params = {
        pageNo: currentPage,
        pageSize,
        ...searchParams
      };
      const response = await CustomerApi.getCustomerPage(params);
      setCustomers(response.data.list || []);
      setTotal(response.data.total || 0);
    } catch (error) {
      message.error('获取客户列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchCustomers();
  }, [currentPage, pageSize, searchParams]);

  // 搜索处理
  const handleSearch = (values: any) => {
    setSearchParams(values);
    setCurrentPage(1);
  };

  // 重置搜索
  const handleReset = () => {
    setSearchParams({});
    setCurrentPage(1);
  };

  // 新增客户
  const handleAdd = () => {
    setEditingCustomer(null);
    setModalVisible(true);
    form.resetFields();
  };

  // 编辑客户
  const handleEdit = (record: CustomerVO) => {
    setEditingCustomer(record);
    setModalVisible(true);
    form.setFieldsValue(record);
  };

  // 删除客户
  const handleDelete = async (id: number) => {
    try {
      await CustomerApi.deleteCustomer(id);
      message.success('删除成功');
      fetchCustomers();
    } catch (error) {
      message.error('删除失败');
    }
  };

  // 锁定/解锁客户
  const handleLock = async (id: number, lockStatus: boolean) => {
    try {
      await CustomerApi.lockCustomer(id, lockStatus);
      message.success(lockStatus ? '锁定成功' : '解锁成功');
      fetchCustomers();
    } catch (error) {
      message.error(lockStatus ? '锁定失败' : '解锁失败');
    }
  };

  // 保存客户
  const handleSave = async (values: CustomerVO) => {
    try {
      if (editingCustomer) {
        await CustomerApi.updateCustomer({ ...editingCustomer, ...values });
        message.success('更新成功');
      } else {
        await CustomerApi.createCustomer(values);
        message.success('创建成功');
      }
      setModalVisible(false);
      fetchCustomers();
    } catch (error) {
      message.error('保存失败');
    }
  };

  // 导出客户
  const handleExport = async () => {
    try {
      await CustomerApi.exportCustomer(searchParams);
      message.success('导出成功');
    } catch (error) {
      message.error('导出失败');
    }
  };

  // 表格列定义
  const columns = [
    {
      title: '客户名称',
      dataIndex: 'name',
      key: 'name',
      width: 150,
      ellipsis: true
    },
    {
      title: '联系方式',
      key: 'contact',
      width: 120,
      render: (record: CustomerVO) => (
        <div>
          <div>{record.mobile}</div>
          <div style={{ fontSize: '12px', color: '#999' }}>{record.email}</div>
        </div>
      )
    },
    {
      title: '客户等级',
      dataIndex: 'level',
      key: 'level',
      width: 100,
      render: (level: number) => {
        const option = levelOptions.find(item => item.value === level);
        return option ? <Tag color="blue">{option.label}</Tag> : '-';
      }
    },
    {
      title: '客户来源',
      dataIndex: 'source',
      key: 'source',
      width: 100,
      render: (source: number) => {
        const option = sourceOptions.find(item => item.value === source);
        return option ? option.label : '-';
      }
    },
    {
      title: '负责人',
      dataIndex: 'ownerUserName',
      key: 'ownerUserName',
      width: 100,
      ellipsis: true
    },
    {
      title: '状态',
      key: 'status',
      width: 100,
      render: (record: CustomerVO) => (
        <Space>
          {record.lockStatus && <Tag color="red">已锁定</Tag>}
          {record.dealStatus && <Tag color="green">已成交</Tag>}
          {record.followUpStatus && <Tag color="orange">跟进中</Tag>}
        </Space>
      )
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 120,
      render: (time: string) => time ? new Date(time).toLocaleDateString() : '-'
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      fixed: 'right' as const,
      render: (record: CustomerVO) => (
        <Space>
          <Tooltip title="编辑">
            <Button
              type="link"
              size="small"
              icon={<EditOutlined />}
              onClick={() => handleEdit(record)}
            />
          </Tooltip>
          <Tooltip title={record.lockStatus ? "解锁" : "锁定"}>
            <Button
              type="link"
              size="small"
              icon={record.lockStatus ? <UnlockOutlined /> : <LockOutlined />}
              onClick={() => handleLock(record.id!, !record.lockStatus)}
            />
          </Tooltip>
          <Popconfirm
            title="确定要删除这个客户吗？"
            onConfirm={() => handleDelete(record.id!)}
            okText="确定"
            cancelText="取消"
          >
            <Tooltip title="删除">
              <Button
                type="link"
                size="small"
                danger
                icon={<DeleteOutlined />}
              />
            </Tooltip>
          </Popconfirm>
        </Space>
      )
    }
  ];

  return (
    <div style={{ padding: '24px' }}>
      <Card>
        <Row gutter={[16, 16]}>
          <Col span={24}>
            <Form
              layout="inline"
              onFinish={handleSearch}
              style={{ marginBottom: '16px' }}
            >
              <Form.Item name="name">
                <Input placeholder="客户名称" />
              </Form.Item>
              <Form.Item name="mobile">
                <Input placeholder="手机号" />
              </Form.Item>
              <Form.Item name="level">
                <Select placeholder="客户等级" style={{ width: 120 }} allowClear>
                  {levelOptions.map(option => (
                    <Option key={option.value} value={option.value}>
                      {option.label}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
              <Form.Item name="source">
                <Select placeholder="客户来源" style={{ width: 120 }} allowClear>
                  {sourceOptions.map(option => (
                    <Option key={option.value} value={option.value}>
                      {option.label}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
              <Form.Item>
                <Space>
                  <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                    搜索
                  </Button>
                  <Button onClick={handleReset} icon={<ReloadOutlined />}>
                    重置
                  </Button>
                </Space>
              </Form.Item>
            </Form>
          </Col>
          <Col span={24}>
            <Space style={{ marginBottom: '16px' }}>
              <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
                新增客户
              </Button>
              <Button icon={<ExportOutlined />} onClick={handleExport}>
                导出
              </Button>
              <Button icon={<ImportOutlined />}>
                导入
              </Button>
            </Space>
          </Col>
        </Row>

        <Table
          columns={columns}
          dataSource={customers}
          rowKey="id"
          loading={loading}
          scroll={{ x: 1200 }}
          pagination={{
            current: currentPage,
            pageSize,
            total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
            onChange: (page, size) => {
              setCurrentPage(page);
              setPageSize(size || 10);
            }
          }}
        />
      </Card>

      {/* 新增/编辑客户弹窗 */}
      <Modal
        title={editingCustomer ? '编辑客户' : '新增客户'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        onOk={() => form.submit()}
        width={800}
        destroyOnClose
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSave}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="name"
                label="客户名称"
                rules={[{ required: true, message: '请输入客户名称' }]}
              >
                <Input placeholder="请输入客户名称" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="mobile"
                label="手机号"
                rules={[
                  { required: true, message: '请输入手机号' },
                  { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }
                ]}
              >
                <Input placeholder="请输入手机号" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="telephone" label="电话">
                <Input placeholder="请输入电话" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="email" label="邮箱">
                <Input placeholder="请输入邮箱" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="level" label="客户等级">
                <Select placeholder="请选择客户等级">
                  {levelOptions.map(option => (
                    <Option key={option.value} value={option.value}>
                      {option.label}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="source" label="客户来源">
                <Select placeholder="请选择客户来源">
                  {sourceOptions.map(option => (
                    <Option key={option.value} value={option.value}>
                      {option.label}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={24}>
              <Form.Item name="detailAddress" label="详细地址">
                <Input placeholder="请输入详细地址" />
              </Form.Item>
            </Col>
            <Col span={24}>
              <Form.Item name="remark" label="备注">
                <Input.TextArea rows={3} placeholder="请输入备注" />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>
    </div>
  );
};

export default CustomerManagement;